package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.common.utils.HttpUtil;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.juli.WebappProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: UserServiceImpl
 * @Author 贾金博
 * @Package com.sky.service.impl
 * @Date 2024/3/28 19:59
 * @description:
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    //微信服务接口
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;
    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //判断openid 是都为空 为空表示业务异常
        String openid = getOpenid(userLoginDTO.getCode());
        if(openid == null || openid.equals("")) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //不为空 判断 当前这个用户的openid 时候在表里面 没有的话 就是新用户 自动注册 把起数据存到数据库里面
        User user = userMapper.getByOpenid(openid);
        //新用户 自动完成注册
        if(user == null || user.equals("")) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        } else {

        }
        // 返回用户对象
        return user;
    }


    /**
     * 调用微信接口服务 获取用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code) {
        //调用微信接口服务 获取当前的微信用户的openid
        Map<String, String>map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type"," authorization_code");

        String s = HttpClientUtil.doGet(WX_LOGIN, map); // 接收返回数据 返回的是json数据
        JSONObject jsonObject = JSON.parseObject(s);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}
